package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.BaseDepartment;
import com.yegs.jltqc.VO.BaseMenu;
import com.yegs.jltqc.common.StoreException;
import com.yegs.jltqc.dao.BaseDepartmentRepository;
import com.yegs.jltqc.dao.BaseMenuRepository;
import com.yegs.jltqc.service.BaseDepartmentService;
import com.yegs.jltqc.service.BaseMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BaseDepartmentServiceImpl implements BaseDepartmentService {

    @Autowired
    private BaseDepartmentRepository baseDepartmentRepository;

    @Override
    public void save(BaseDepartment baseMenu) throws StoreException{
        if(baseMenu.getId() == null){
            BaseDepartment menu = baseDepartmentRepository.findBaseDepartmentByName(baseMenu.getName());
            if(menu != null){
                throw new StoreException("菜单已存在!");
            }
            baseDepartmentRepository.save(baseMenu);
        }else{
            BaseDepartment menu = baseDepartmentRepository.getOne(baseMenu.getId());
            if(menu == null){
                throw new StoreException("系统错误!");
            }
            menu.setName(baseMenu.getName());
            baseDepartmentRepository.save(menu);
        }

    }

    @Override
    public List<BaseDepartment> list() {
        return baseDepartmentRepository.findAll();
    }

    @Override
    public BaseDepartment get(Long id) {
        return baseDepartmentRepository.getOne(id);
    }

    @Override
    public void del(Long id) {
        baseDepartmentRepository.deleteById(id);
    }

    @Override
    public Page<BaseDepartment> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        if(query.getName() == null || query.getName().trim() == ""){
            return baseDepartmentRepository.findAll(request);
        }
        return baseDepartmentRepository.findBaseDepartmentByName(query.getName(), request);
    }

}


